package com.gutai.admin.service.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;

import com.gutai.admin.common.util.IdGeneratorUtil;
import com.gutai.admin.dao.IBrandDao;
import com.gutai.admin.entity.Brand;
import com.gutai.admin.service.IBrandService;

/**
 * 
 * 描述：
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年11月7日         YC           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author YC
 * @version 1.0
 */
@Service
@CacheConfig(cacheNames = "brands")
public class BrandsService implements IBrandService {

    @Autowired
    private IBrandDao brandDao;
    @Autowired
    private IBrandService brandsService;
    
    private static final Set<String> enabledFields = new HashSet<>(Arrays.asList("id","name","floor_price","app_list_pic_url"));

    @Override
    public Page<Brand> getList2MiniPro(int pageIdx, int pageSize) {
        return brandDao.queryPageWithSelect(enabledFields, pageIdx, pageSize);
    }

    @Override
    public List<Brand> getList(String name) {
//        return brandDao.findByName(name);
        return brandsService.getAll().stream().filter(item -> item.getName().indexOf(name) >= 0)
                .collect(Collectors.toList());
    }

    @Override
    @Cacheable(unless = "#result == null || #result.size()==0")
    public List<Brand> getAll() {
        Sort sort = new Sort(Direction.DESC, "createTime");
        return brandDao.findAll(sort);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void add(Brand entity) {
        entity.setId(IdGeneratorUtil.generate());
        entity.setAppListPicUrl(entity.getListPicUrl());
        entity.setNewPicUrl(entity.getPicUrl());
        brandDao.save(entity);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void update(Brand entity) {
        entity.setAppListPicUrl(entity.getListPicUrl());
        entity.setNewPicUrl(entity.getPicUrl());
        brandDao.saveAndFlush(entity);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void delete(int id) {
        brandDao.deleteById(id);
    }


    @Override
    public Brand findById(int id) {
        return brandDao.findById(id);
    }

}
